package com.pig4cloud.pigx.common.customize.api.filter.multi;

import cn.hutool.core.io.IoUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 自定义请求包装器，为了实现从请求体中多次读取数据
 *
 * @since 2022/11/12 20:23
 */
public class MultiReadBodyRequestWrapper extends HttpServletRequestWrapper {

	private final byte[] body;

	public MultiReadBodyRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);

		// 缓存请求体
		body = IoUtil.readBytes(request.getInputStream());
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	/**
	 * 重写，使其返回缓存的请求体数据
	 *
	 * @return {@link ServletInputStream}
	 * @since 2022/11/12 20:26
	 */
	@Override
	public ServletInputStream getInputStream() throws IOException {

		final ByteArrayInputStream bais = new ByteArrayInputStream(body);

		return new ServletInputStream() {

			@Override
			public int read() throws IOException {
				return bais.read();
			}

			@Override
			public boolean isFinished() {
				return false;
			}

			@Override
			public boolean isReady() {
				return false;
			}

			@Override
			public void setReadListener(ReadListener readListener) {

			}
		};
	}
}
